package com.jh3502.vivo.function.travelnew;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jh3502.vivo.R;
import com.jh3502.vivo.base.BaseActivity;
import com.jh3502.vivo.function.citylist.CityBean;
import com.jh3502.vivo.function.citylist.CityListActivity;
import com.jh3502.vivo.function.contact.ContactActivity;
import com.jh3502.vivo.function.contact.ContactBean;
import com.jh3502.vivo.function.dialog.DialogList;
import com.jh3502.vivo.function.dialog.DialogReason;
import com.jh3502.vivo.function.dialog.PhotoChooseDialog;
import com.jh3502.vivo.utils.Utils;
import com.jh3502.vivo.view.MyRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * author:harisucici on 2018/11/7 10:42
 * email:harisucici@gmail.com
 * name:
 * todo:
 */
public class TravelNewActivity extends BaseActivity<TravelNewPresenter.TravelNewView, TravelNewPresenter> implements TravelNewPresenter.TravelNewView {
    public static final int FROM_CITY_CHOOSE = 001;
    public static final int FROM_CAR_CHOOSE = 002;
    public static final int FROM_OUT1_CHOOSE = 003;
    public static final int FROM_OUT2_CHOOSE = 004;
    public static final int FROM_PERSON_CHOOSE = 005;
    public static final int FROM_REASON_CHOOSE = 006;
    public static final int FROM_ITEM_PHOTO_CHOOSE = 7;

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.travel_new_date1)
    TextView travelNewDate1;
    @BindView(R.id.travel_new_date2)
    TextView travelNewDate2;
    @BindView(R.id.travel_new_days)
    TextView travelNewDays;
    @BindView(R.id.travel_new_place)
    TextView travelNewPlace;
    @BindView(R.id.travel_new_person)
    TextView travelNewPerson;
    @BindView(R.id.travel_new_car)
    TextView travelNewCar;
    @BindView(R.id.travel_new_out2)
    TextView travelNewOut2;
    @BindView(R.id.travel_new_out1)
    TextView travelNewOut1;
    @BindView(R.id.travel_new_reason)
    TextView travelNewReason;
    @BindView(R.id.travel_new_photo)
    MyRecyclerView travelNewPhoto;
    @BindView(R.id.travel_new_cancel)
    TextView travelNewCancel;
    @BindView(R.id.travel_new_submit)
    TextView travelNewSubmit;
    @BindView(R.id.travel_new_photo_add)
    ImageView travelNewPhotoAdd;
    @BindView(R.id.travel_new_no)
    TextView travelNewNo;
    private TimePickerView timePickerView;
    private Date date1 = new Date(), date2 = new Date();
    private int chosen = -1;
    private String[] cars = {"否", "是"};
    private String[] outs1 = {"否", "是"};
    private String[] outs2 = {"火车票卖完了", "火车票比飞机票贵"};
    private PhotoChosenAdapter mAdapter;
    private int maxphotos = 1;
    private List<CityBean> list = new ArrayList<>(2);
    private int isdriver = -1, overtop = -1;
    private List<ContactBean> personsChosen = new ArrayList<>(2);
    private List<Map<String, Object>> personsChosenNew = new ArrayList<>(2);
    private List<String> pics = new ArrayList<>(2);
    private String oldJson = "";
    private TravelNewBean bean;


    @Override
    public TravelNewPresenter initPresenter() {
        return new TravelNewPresenter();
    }

    @Override
    protected int setViewId() {
        return R.layout.activity_travel_new;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("出差");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mPresenter.setTravelNewView(this);


        StaggeredGridLayoutManager staggeredGridLayoutManager =
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mAdapter = new PhotoChosenAdapter(this, pics);

        travelNewPhoto.setLayoutManager(staggeredGridLayoutManager);
        travelNewPhoto.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(s -> {

        });
        mAdapter.setButtonSetOnclickDelete(position -> {
            pics.remove(position);
            travelNewPhotoAdd.setVisibility(View.VISIBLE);
            mAdapter.notifyDataSetChanged();
        });

        Intent intent = getIntent();
        if (intent != null) {
            Map<String, Object> body = new HashMap<>(2);
            body.put("id", intent.getExtras().getInt("id"));
            mPresenter.toGetTravelById(body);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
        }
        return true;
    }

    @Override
    protected void initData() {
        timePickerView = initCustomTimePicker("出差申请", R.layout.pickerview_custom_time);
    }


    private TimePickerView initCustomTimePicker(String title, int layout) {
        Calendar selectedDate = Calendar.getInstance();
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(this, (date, v) -> {
            if (chosen == 1) {
                date1 = date;
                travelNewDate1.setText(Utils.getInstance().getDate(date));
            } else if (chosen == 2) {
                date2 = date;
                travelNewDate2.setText(Utils.getInstance().getDate(date));
            }
        });
        timePickerBuilder.setDividerColor(Color.TRANSPARENT)
                .setTextColorOut(Color.parseColor("#FF969696"))
//                .setTextColorCenter(Color.parseColor("#FFFFFF"))
                .setTextColorCenter(Color.WHITE)
                .setLineSpacingMultiplier(6f)
                .setBgColor(Color.TRANSPARENT)
                .setDate(selectedDate)
                .setContentTextSize(18)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false)
                .isDialog(true)
                .setLayoutRes(layout, v -> {
                    TextView date_picker_title = v.findViewById(R.id.date_picker_title);
                    TextView date_picker_submit = v.findViewById(R.id.date_picker_submit);
                    TextView date_picker_cancel = v.findViewById(R.id.date_picker_cancel);
                    date_picker_title.setText(title);
                    date_picker_submit.setOnClickListener(v1 -> {
                        timePickerView.returnData();
                        timePickerView.dismiss();

                    });
                    date_picker_cancel.setOnClickListener(v12 -> {
                        timePickerView.dismiss();
                    });
                });
        timePickerView = timePickerBuilder.build();
        return timePickerView;
    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public void responseError(int code, String msg) {

    }

    @OnTextChanged(value = R.id.travel_new_date1, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedDate1(CharSequence s, int start, int before, int count) {
        if (travelNewDate2.getText().toString().trim().length() > 0) {
            if (date1 == null || date2 == null) {
                return;
            }
            int days = Utils.getInstance().getDateCount(date1, date2);
            if (days < 0) {
                travelNewDays.setText("日期选择有误");
            } else {
                travelNewDays.setText(days + "天");
            }

        }
    }

    @OnTextChanged(value = R.id.travel_new_date2, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedDate2(CharSequence s, int start, int before, int count) {
        if (travelNewDate1.getText().toString().trim().length() > 0) {
            if (date1 == null || date2 == null) {
                return;
            }
            int days = Utils.getInstance().getDateCount(date1, date2);
            if (days < 0) {
                travelNewDays.setText("日期选择有误");
            } else {
                travelNewDays.setText(days + "天");
            }
        }
    }

    @OnClick(R.id.travel_new_date1)
    public void onTravelNewDate1Clicked() {
        chosen = 1;
        timePickerView.show();
    }

    @OnClick(R.id.travel_new_date2)
    public void onTravelNewDate2Clicked() {
        chosen = 2;
        timePickerView.show();
    }


    @OnClick(R.id.travel_new_place)
    public void onTravelNewPlaceClicked() {
        Intent intent = new Intent(getActContext(), CityListActivity.class);
        startActivityForResult(intent, FROM_CITY_CHOOSE);
    }

    @OnClick(R.id.travel_new_person)
    public void onTravelNewPersonClicked() {
        Intent intent = new Intent(getActContext(), ContactActivity.class);
        startActivityForResult(intent, FROM_PERSON_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FROM_CITY_CHOOSE:
                    list.clear();
                    list = new Gson().fromJson(data.getStringExtra("dataChosen"),
                            new TypeToken<List<CityBean>>() {
                            }.getType());


                    StringBuffer stringBuffer = new StringBuffer();
                    for (CityBean cityBean : list) {
                        stringBuffer.append(cityBean.getName());
                        stringBuffer.append("、");

                    }
                    travelNewPlace.setText(
                            stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                    break;
                case FROM_PERSON_CHOOSE:
                    personsChosen.clear();
                    personsChosen = new Gson().fromJson(data.getStringExtra("datachosen"),
                            new TypeToken<List<ContactBean>>() {
                            }.getType());
                    StringBuffer stringBufferContact = new StringBuffer();
                    for (ContactBean contactBean : personsChosen) {
                        stringBufferContact.append(contactBean.getName());
                        stringBufferContact.append("、");

                    }
                    travelNewPerson.setText(
                            stringBufferContact.toString().substring(0, stringBufferContact.toString().length() - 1));

                    break;
                case FROM_CAR_CHOOSE:
                    isdriver = data.getIntExtra("chosen", -1);
                    travelNewCar.setText(cars[isdriver]);
                    break;
                case FROM_REASON_CHOOSE:
                    travelNewReason.setText(data.getStringExtra("reason"));
                    break;
                case FROM_OUT1_CHOOSE:
                    int chosen = data.getIntExtra("chosen", 0);
                    travelNewOut1.setText(outs1[chosen]);
                    if (chosen == 1) {
                        travelNewOut1.setTextColor(Color.parseColor("#FFF36C60"));
                    } else {
                        travelNewOut1.setTextColor(Color.parseColor("#FF999999"));
                    }
                    break;
                case FROM_OUT2_CHOOSE:
                    overtop = data.getIntExtra("chosen", -1);
                    travelNewOut2.setText(outs2[overtop]);
                    break;
                case FROM_ITEM_PHOTO_CHOOSE:
                    pics.add(data.getStringExtra("path"));
                    mAdapter.notifyDataSetChanged();
                    if (pics.size() == maxphotos) {
                        travelNewPhotoAdd.setVisibility(View.GONE);
                    }
                    break;
//                case Constant.REQUEST_CODE_IMAGE:
//                    path = UploadHelper.getInstance().getImageAbsolutePath(this, data.getData());
//                    photos.add(new File(path));
//
//                    mAdapter.notifyDataSetChanged();
//                    break;
//                case Constant.REQUEST_CODE_CAMERA:
//                    photos.add(mCamareFile);
//                    if (photos.size() == maxphotos) {
//                        travelNewPhotoAdd.setVisibility(View.GONE);
//                    }
//                    mAdapter.notifyDataSetChanged();
//                    break;


                default:
            }
        }
    }


    @OnClick(R.id.travel_new_car)
    public void onTravelNewCarClicked() {
        Intent intent = new Intent(getActContext(), DialogList.class);
        intent.putExtra("title", "选择是否带车");
        intent.putExtra("list", cars);
        startActivityForResult(intent, FROM_CAR_CHOOSE);
    }


    @OnClick(R.id.travel_new_out1)
    public void onTravelNewOut1Clicked() {
        Intent intent = new Intent(getActContext(), DialogList.class);
        intent.putExtra("title", "选择是否超标");
        intent.putExtra("list", outs1);
        startActivityForResult(intent, FROM_OUT1_CHOOSE);
    }

    @OnClick(R.id.travel_new_out2)
    public void onTravelNewOut2Clicked() {
        Intent intent = new Intent(getActContext(), DialogList.class);
        intent.putExtra("title", "选择超标理由");
        intent.putExtra("list", outs2);
        startActivityForResult(intent, FROM_OUT2_CHOOSE);
    }


    @OnClick(R.id.travel_new_photo)
    public void onTravelNewPhotoClicked() {
    }

    @OnClick(R.id.travel_new_cancel)
    public void onTravelNewCancelClicked() {
    }

    @OnClick(R.id.travel_new_submit)
    public void onTravelNewSubmitClicked() {
        upLoadTravel();

    }

    @OnClick(R.id.travel_new_photo_add)
    public void onTravelNewPhotoAddClicked() {
        Intent intent = new Intent(this, PhotoChooseDialog.class);
        startActivityForResult(intent, FROM_ITEM_PHOTO_CHOOSE);

    }


    @Override
    public void sumtravelSuccess() {
        showShortToast("提交成功");
        onBackPressed();
    }


    private void upLoadTravel() {
        Map<String, Object> bodyAll = new HashMap<>(2);
        String businessNo = travelNewNo.getText().toString().trim();
        Map<String, Object> body = new HashMap<>(2);
        body.put("businessNo", businessNo);
        body.put("startdate", travelNewDate1.getText().toString());
        body.put("enddate", travelNewDate2.getText().toString());
        body.put("destination", list);
        for (ContactBean contactBean : personsChosen) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", contactBean.getName());
            map.put("userId", contactBean.getUserId());
            personsChosenNew.add(map);
        }
        body.put("person", personsChosenNew);
        body.put("isdriver", isdriver);
        body.put("overtop", overtop);
        body.put("reason", travelNewOut2.getText().toString().trim());
        body.put("businesstrip", travelNewReason.getText().toString().trim());
        body.put("enclosure", pics);
        bodyAll.put("oldJson", oldJson);
        bodyAll.put("newJson", body);
        mPresenter.toSumtravel(bodyAll);
    }

    @Override
    public void getTravelByIdSuccess(String data) {
        oldJson = data;
        bean = new Gson().fromJson(oldJson, TravelNewBean.class);
        travelNewNo.setText(bean.getBusinessNo());
        travelNewDate1.setText(bean.getStartdate());
        travelNewDate2.setText(bean.getEnddate());
        date1 = Utils.getInstance().string2Date(bean.getStartdate());
        date2 = Utils.getInstance().string2Date(bean.getEnddate());
        travelNewDays.setText(Utils.getInstance().getDateCount(date1, date2) + "天");
        list = new Gson().fromJson(bean.getDestination(),
                new TypeToken<List<CityBean>>() {
                }.getType());
        StringBuffer stringBufferCity = new StringBuffer();
        for (CityBean cityBean : list) {
            stringBufferCity.append(cityBean.getName());
            stringBufferCity.append("、");
        }
        travelNewPlace.setText(
                stringBufferCity.toString().substring(0, stringBufferCity.toString().length() - 1));
        personsChosen = new Gson().fromJson(bean.getPerson(),
                new TypeToken<List<ContactBean>>() {
                }.getType());
        StringBuffer stringBuffer = new StringBuffer();
        for (ContactBean contactBean : personsChosen) {
            stringBuffer.append(contactBean.getName());
            stringBuffer.append("、");

        }
        travelNewPerson.setText(
                stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));

        isdriver = bean.getIsdriver();
        if (isdriver == 1) {
            travelNewCar.setText("是");

        } else {
            travelNewCar.setText("否");
        }

        overtop = bean.getOvertop();
        if (overtop == 1) {
            travelNewOut1.setText("是");
            travelNewOut1.setTextColor(Color.parseColor("#FFF36C60"));
        } else {
            travelNewOut1.setText("否");
            travelNewOut1.setTextColor(Color.parseColor("#FF999999"));

        }
        travelNewOut2.setText(bean.getReason());
        travelNewReason.setText(bean.getBusinesstrip());
        pics.addAll(Utils.getInstance().jsa2listString(bean.getEnclosure()));
        mAdapter.notifyDataSetChanged();
    }


    @OnClick(R.id.travel_new_reason)
    public void onTravelNewReasonClicked() {
        Intent intent = new Intent(getActContext(), DialogReason.class);
        startActivityForResult(intent, FROM_REASON_CHOOSE);
    }
}
